package com.hbnu.controller;

import com.hbnu.pojo.User;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
//@RestController //被RestController注解修饰的类中所有的方法返回的是数据，而不是视图，RestController注解其实就是Controller注解和ResponseBody注解的组合
public class HomeController {

    @RequestMapping("/home")
    public String homePage(){
        return "home";
    }

    @RequestMapping("/param1")
    @ResponseBody  //返回的是数据 如果想返回页面就不需要加
    public void param1(String name, Integer age){
        System.out.println("接收到的参数：" + name + "---->" + age);
    }

    @RequestMapping("/param2")
    @ResponseBody
    public String param2(User user){
        System.out.println("接受到的用户数据: " + user);
        return "success ! ! !";
    }

    @RequestMapping("/param3")
    @ResponseBody
    public void param3(Date date){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        System.out.println("接收到的日期： " + date);
        System.out.println("格式化后的日期： " + simpleDateFormat.format(date));
    }

//    自定义时间格式
    @InitBinder
    public void initBinder(ServletRequestDataBinder binder){
        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
    }


//    转发(地址栏不会变）
    @RequestMapping("/forward")
    public String testForward(){
        System.out.println("我处理不了......,我找人处理");
        return "forward:home";
    }


//    重定向(地址栏会变）
    @RequestMapping("/redirect")
    public String testRedirect(){
        System.out.println("我不想处理，你找别人吧....");
        return "redirect:home";
    }

    @RequestMapping(value = "/character",produces = "text/json;charset=utf-8")
    @ResponseBody
    public String character(){
        return "这是中文，看的清楚吗";
    }

    @RequestMapping("/userInfo")
    public String userInfo(Model model){
        model.addAttribute("name", "Lily");
        model.addAttribute("address", "Chinese");
        return "home";
    }

    @RequestMapping("/findAllUser")
    @ResponseBody
    public List<User> findAllUser(){
        List<User> userList = new ArrayList<>();

        userList.add(new User(2, "丽娘", "花园", 17));
        userList.add(new User(3, "镜玄", "花园", 18));
        userList.add(new User(4, "李清照", "仙苑", 24));
        userList.add(new User(5, "陶渊明", "菊园", 35));

        return userList;
    }

}





















